<template>
  <!-- 机构管理 -->
  <div class="module_par">
    <div class="module_con">
      <!-- 搜索区域 -->
      <div class="search_box">
        <el-row :gutter="20">
          <el-col :span="6">
            <span class="inpText">机构名称:</span>
            <el-input v-model="searchBox.name" autocomplete="off" size="small" class="searchInp"></el-input>
          </el-col>
          <el-col :span="6">
            <span class="inpText">机构编号:</span>
            <el-input v-model="searchBox.code" autocomplete="off" size="small" class="searchInp"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" size="small" @click="goSearch" v-if="$requestBtnApi.organ.queryBtn">查询</el-button>
            <el-button type="primary" size="small" @click="resetData">重置</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- 主体内容 -->
      <div class="table-content">
        <el-table :data="tableData" border tooltip-effect="dark" style="width: 100%" row-key="id" highlight-current-row
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column type="index" align="center" label="#"></el-table-column>
          <el-table-column prop="name" label="机构名称"></el-table-column>
          <el-table-column prop="code" align="center" label="机构编号"></el-table-column>
          <el-table-column prop="tenantName" align="center" label="所属租户"></el-table-column>
          <!-- <el-table-column prop="createUser" align="center" label="创建人"></el-table-column>
          <el-table-column prop="createTime" align="center" label="创建时间"></el-table-column>-->
          <el-table-column prop="updateUser" align="center" label="修改人"></el-table-column>
          <el-table-column prop="updateTime" align="center" label="修改时间"></el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <a class="table_a" @click="addData(scope.row)" v-if="$requestBtnApi.organ.addBtn">
                <i class="el-icon-circle-plus-outline"></i>新 增
              </a>
               <a class="table_a table_a_left" @click="editData(scope.row)" v-if="scope.row.type != 'T' && $requestBtnApi.organ.editBtn">
                <i class="el-icon-edit"></i>编 辑
              </a>
              <a class="table_a table_a_left table_a_del" @click="delData(scope.row)" v-if="scope.row.type != 'T' && !scope.row.children.length && $requestBtnApi.organ.delBtn">
                <i class="el-icon-delete"></i>删 除
              </a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 弹框区域 -->
      <!-- 新增    编辑 -->
      <el-dialog :title="tit" :visible.sync="dialogSta">
        <el-form label-width="100px" :model="dialogData" :rules="roules" ref="ruleForm">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="机构编号" prop="code">
                <el-input v-model="dialogData.code" autocomplete="off" size="small" class="searchInp"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机构名称" prop="name">
                <el-input v-model="dialogData.name" autocomplete="off" size="small" class="searchInp"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="tit== '新增机构'">
            <el-col :span="12">
              <el-form-item label="上级机构">
                <el-input v-model="dialogData.parentName" autocomplete="off" size="small" class="searchInp" disabled></el-input>
              </el-form-item>
            </el-col>

            <!-- <el-col :span="12">
              <el-form-item label="委外公司">
                <el-switch v-model="isDelegateCompany" active-text="是" inactive-text="否">
                </el-switch>
              </el-form-item>
            </el-col> -->
          </el-row>

          <!-- <el-row :gutter="20" v-if="isDelegateCompany">
            <el-col :span="12">
              <el-form-item label="开始时间">
                <el-date-picker v-model="companyInfo.startTime" type="date" size="small" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" class="searchInp"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间">
                <el-date-picker v-model="companyInfo.endTime" type="date" size="small" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  class="searchInp"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="isDelegateCompany">
            <el-col :span="12">
              <el-form-item label="佣金比率">
                <el-input v-model="companyInfo.profitMarginStr" onkeyup="if(value<1)value=1;if(value>100)value=100;"
                  min="1" max="100" step="1" @input="handleInput" type="number" size="small" class="searchInp">
                  <el-button slot="append">%</el-button>
                </el-input>
              </el-form-item>
            </el-col>

          </el-row> -->

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogSta = false" size="small">取 消</el-button>
          <el-button type="primary" @click="dataPost('ruleForm')" size="small">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { baseUrl } from '../../../static/baseUrl'
  export default {
    data() {

      return {
        isDelegateCompany: false, //是否委外公司
        companyInfo: {},
        // table数据
        tableData: [],
        // 搜索字段
        searchBox: {
          code: "",
          name: "",
        },
        // 查询状态
        searchSta: false,
        // 弹框状态
        dialogSta: false,
        // 弹框title
        tit: "",
        // 弹框数据
        dialogData: {
          name: "",
          code: "",
          parentId: "",
          parentCode: "",
          tenantName: "",
          parentName: "",
          startTime: "",
          endTime: "",
        },
        // 正则校验
        roules: {
          name: [{
            required: true,
            message: "请输入机构名称",
            trigger: "blur"
          }, {
            required: true,
            validator: (rule, value, callback) => {
              if (value != "") {
                const data = {
                  name: this.dialogData.name,
                  //code: this.dialogData.code,
                };
                this.$requestA.get("/organ/getCodeOrName", data, (res) => {
                  if (res.data.code == 200) {
                    callback();
                  } else {
                    callback(new Error("机构名称已存在，请重新输入"));
                  }
                })

              } else {
                callback(new Error("请输入机构名称"));
              }
            },
            trigger: "blur"
          }],
          code: [{
            required: true,
            message: "请输入机构编号",
            trigger: "blur"
          }, {
            required: true,
            validator: (rule, value, callback) => {
              if (value != "") {
                const data = {
                // name: this.dialogData.name,
                 code: this.dialogData.code,
                };
                this.$requestA.get("/organ/getCodeOrName", data, (res) => {
                  if (res.data.code == 200) {
                    callback();
                  } else {
                    callback(new Error("机构编号已存在，请重新输入"));
                  }
                })

              } else {
                callback(new Error("请输入机构编号"));
              }
            },
            trigger: "blur"
          }],
        },
        // 编辑当前数据
        editDataList: null,

      };
    },
    methods: {
      //保留两位小数
      handleInput(value) {
        if (value != '') {
          if (value.indexOf('.') > -1) {
            this.companyInfo.profitMarginStr = value.slice(0, value.indexOf('.') + 3);
          } else {
            this.companyInfo.profitMarginStr = value;
          }
        }
      },
      //添加委外公司信息
      addCompany(data) {
        this.$axios({
            method: "post",
            url: `${baseUrl}//organAndOutsourcingCompany`,
            data: data,
          })
          .then((res) => {
            if (res.code == "200") {
              console.log("res==", res);
              this.$message.success("新增委外公司成功!");
              this.dialogSta = false;
              this.getTableList();
            }
          })
          .catch((err) => {
            console.log(err)
          });
      },
      // 弹框确定
      dataPost(formName) {
        if (this.tit == "新增机构") {
          this.$refs[formName].validate((valid) => {
              if (valid) {
                const data = {
                  name: this.dialogData.name,
                  code: this.dialogData.code,
                  parentId: this.dialogData.parentId,
                  tenantCode: this.dialogData.parentCode,
                  tenantName: this.dialogData.tenantName,
                };

                if (this.dialogData.code == "") {
                  this.$message.warning("请输入机构编号");
                  return false;
                } else if (this.dialogData.name == "") {
                  this.$message.warning("请输入机构名称");
                  return false;
                }
                //
                if (this.isDelegateCompany) {
                  if (undefined == this.companyInfo.startTime || this.companyInfo.startTime == "") {
                    this.$message.warning("请指定委外公司的开始时间！");
                    return false;
                  } else if (undefined == this.companyInfo.endTime || this.companyInfo.endTime == "") {
                    this.$message.warning("请指定委外公司的结束时间！");
                    return false;
                  } else if (undefined == this.companyInfo.profitMarginStr || this.companyInfo.profitMarginStr == "") {
                    this.$message.warning("请指定委外公司的佣金比率！");
                    return false;
                  } else {

                    let tmpStr = this.companyInfo.profitMarginStr;
                    let tmpPercent = tmpStr + "%";
                    let profitMargin = this.toPoint(tmpPercent);
                    this.$set(this.companyInfo, "profitMargin", profitMargin);
                  }
                }
                //添加委外机构
                if (this.isDelegateCompany) {
                  this.$set(this.companyInfo, "name", this.dialogData.name),
                  this.$set(this.companyInfo, "code", this.dialogData.code),
                  this.$set(this.companyInfo, "tenantName", this.dialogData.tenantName),
                  this.$set(this.companyInfo, "tenantCode", this.dialogData.parentCode),
                  this.$set(this.companyInfo, "parentId", this.dialogData.parentId),
                  this.$set(this.companyInfo, "updateTime", new Date()),
                  this.$set(this.companyInfo, "updatePeople", localStorage.getItem('USER_CODE')),
                  //this.$set(this.companyInfo, "mechanismId", organId);
                  this.$set(this.companyInfo, "bank", this.dialogData.parentName);
                  this.$set(this.companyInfo, "outsourcingCompany", this.dialogData.name);
                  this.$set(this.companyInfo, "state", 1); //1起效
                  this.$set(this.companyInfo, "category", 1); //1网贷

                  this.addCompany(this.companyInfo);
                } else {
                  this.$requestA[this.$requestBtnApi.organ.addType](
                    this.$requestBtnApi.organ.addUrl,
                    data,
                    (res) => {
                      if (res.code == "200") {
                        this.$message.success("新增机构成功");
                        this.dialogSta = false;
                        this.getTableList();
                      }
                    }
                  );
                }
              }
          })
        } else if (this.tit == "编辑机构") {
          this.editDataList.name = this.dialogData.name;
          this.editDataList.code = this.dialogData.code;
          this.$requestA[this.$requestBtnApi.organ.editType](
            this.$requestBtnApi.organ.editUrl,
            this.editDataList,
            (res) => {
              if (res.code == "200") {
                this.$message.success("编辑机构成功");
                this.dialogSta = false;
                this.getTableList();
              }
            }
          );
        }
      },
      // 重置按钮
      resetData() {
        this.searchBox.name = "";
        this.searchBox.code = "";
        this.searchSta = false;
        this.getTableList();
      },
      // 查询按钮
      goSearch() {
        this.searchSta = true;
        this.getTableList();
      },
      // 新增按钮
      addData(val) {
        this.tit = "新增机构";
        this.dialogSta = true;
        this.$nextTick(() => {
          this.$refs.ruleForm.resetFields();
          this.dialogData.parentId = val.id;
          this.dialogData.parentCode = val.tenantCode;
          this.dialogData.tenantName = val.tenantName;
          this.dialogData.parentName = val.name;
          this.dialogData.code = "";
          this.dialogData.name = "";
        });
      },
      // 编辑按钮
      editData(val) {
        console.log(val);
        this.tit = "编辑机构";
        this.editDataList = val;
        this.dialogSta = true;
        this.$nextTick(() => {
          this.$refs.ruleForm.resetFields();
          this.dialogData.code = val.code;
          this.dialogData.name = val.name;
        });
      },
      // 删除按钮
      delData(val) {
        this.$confirm("此操作将永久删除该数据及子项, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            this.$requestA[this.$requestBtnApi.organ.delType](
              this.$requestBtnApi.organ.delUrl + "/" + val.id, {},
              (res) => {
                if (res.code == "200") {
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  this.dialogSta = false;
                  this.getTableList();
                }
              }
            );
          })
          .catch(() => {});
      },
      // 查询table数据
      getTableList() {
        const data = {
          loginCode: localStorage.getItem("loginCode"),
          tenantCode: localStorage.getItem("TENANT_CODE"),
          name: this.searchSta ? this.searchBox.name : "",
          code: this.searchSta ? this.searchBox.code : "",
        };
        this.$requestA[this.$requestBtnApi.organ.queryType](
          this.$requestBtnApi.organ.queryUrl,
          data,
          (res) => {
            this.tableData = res.data;
          }
        );
      },
      //百分数转小数
      toPoint(percent) {
        var str = percent.replace("%", "");
        str = str / 100;
        return str;
      },
      //小数转百分数
      toPercent(point) {
        var percent = Number(point * 100).toFixed(1);
        percent += "%";
        return percent;
      },
    },
    created() {
      this.$route.meta.menuList.map((item) => {
        if (item.eleName == "查询") {
          this.$requestBtnApi.organ.queryUrl = item.eleUrl;
          this.$requestBtnApi.organ.queryType =
            item.operType == "delete" ? "dele" : item.operType;
          this.$requestBtnApi.organ.queryBtn = true;
        } else if (item.eleName == "新增") {
          this.$requestBtnApi.organ.addUrl = item.eleUrl;
          this.$requestBtnApi.organ.addType =
            item.operType == "delete" ? "dele" : item.operType;
          this.$requestBtnApi.organ.addBtn = true;
        } else if (item.eleName == "编辑") {
          this.$requestBtnApi.organ.editUrl = item.eleUrl;
          this.$requestBtnApi.organ.editType =
            item.operType == "delete" ? "dele" : item.operType;
          this.$requestBtnApi.organ.editBtn = true;
        } else if (item.eleName == "删除") {
          this.$requestBtnApi.organ.delUrl = item.eleUrl;
          this.$requestBtnApi.organ.delType =
            item.operType == "delete" ? "dele" : item.operType;
          this.$requestBtnApi.organ.delBtn = true;
        }
      });
      this.getTableList();
    },


  };
</script>

<style scoped>
  @import "../../assets/css/base.css";

  .search_box {
    background: #fff;
    border-radius: 5px;
    padding: 40px 40px 60px 40px;
    margin: 0 0 20px 0;
  }

  .box_center {
    text-align: left;
  }

  .searchBtn {
    margin-left: 80px;
  }
</style>
